package com.example.blades.mydatepickerdialog;

import android.app.AlertDialog;
import android.icu.text.SimpleDateFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.view.View;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.widget.Button;
import android.widget.DatePicker;
import android.view.View.OnClickListener;
import android.app.DatePickerDialog;
import android.widget.Toast;

public class DatePickerEx extends AppCompatActivity {
    private TextView showdate;
    private Button setdate;
  //  private Date date=null;
    private int year;
    private int month;
    private int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_date_picker_ex);

        showdate=(TextView) this.findViewById(R.id.showdate);
        setdate=(Button) this.findViewById(R.id.setdate);

        Calendar c=Calendar.getInstance(Locale.CHINA);
        Date mydate=new Date();

        c.setTime(mydate);
        year=c.get(Calendar.YEAR);
        month=c.get(Calendar.MONTH);
        day=c.get(Calendar.DAY_OF_MONTH);
        showdate.setText("Current Time:"+year+"-"+(month+1)+"-"+day);

        setdate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog myDatePickerDialog=new DatePickerDialog(DatePickerEx.this,Datelistener,year,month,day);
                myDatePickerDialog.show();
            }
        });

    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener() {
        Date current_date=new Date();

        @Override
        public void onDateSet(DatePicker view, int ye, int mo, int dayOfMonth) {

            Date date=new Date(ye-1900,mo,dayOfMonth);
            if(date.getTime()<=current_date.getTime())
            {
                year=ye;
                month=mo;
                day=dayOfMonth;

                updateDate();
            }
            else
            {
                Toast.makeText(DatePickerEx.this,"Time is invalid",Toast.LENGTH_SHORT).show();
            }

        }

        private void updateDate()
        {
            showdate.setText("Current Time:"+year+"-"+(month+1)+"-"+day);
        }


    };
}
